import React from 'react';
import Util from 'util/mm.jsx';
import User from 'service/user-service.jsx';
import './index.scss';

const _util = new Util();
const _user = new User();

class Login extends React.Component{
	
	constructor(props){
		super(props);
		this.state = {
			username:'',
			password:'',
			redirect:_util.getUrlParam('redirect')
		}
	}
	
	componentWillMount(){
		document.title = '登录 - DEMON MALL ADMIN';
	}
	
	handleChange(e){
		this.setState({
			[e.target.name]:e.target.value
		});
	}
	
	handleLogin(){
		const loginInfo = {username:this.state.username,password:this.state.password};
		const checkResult = _user.checkLoginInfo(loginInfo);
		if(checkResult.status){
			_user.login(loginInfo)
				 .then((res) => {
					 _util.setStorage('userInfo',res);
					 this.props.history.push(this.state.redirect)
				},(errMsg) => {
					_util.errorTips(errMsg);
				});
		}else{
			_util.errorTips(checkResult.msg);
		}
		
	}
	HandleKeyUp(e){
		if(e.keyCode ===13){
			this.handleLogin();
		}
	}
	render(){
		return (
			<div className="col-md-4 col-md-offset-4">
				<div className="panel panel-primary login-panel">
					<div className="panel-heading">
						<h3 className="panel-title">欢迎登录 - DEMON MALL管理系统</h3>
					</div>
					<div className="panel-body">
					
						<div>
							<div className="form-group">
								<input type="text"
									name="username"
									className="form-control"
									placeholder="请输入用户名"
									onChange={e => this.handleChange(e)}
									onKeyUp={e => this.HandleKeyUp(e)}	/>
							</div>
							<div className="form-group">
								<input type="password" 
									name="password"
									className="form-control" 
									placeholder="请输入密码" 
									onChange={e => this.handleChange(e)}
									onKeyUp={e => this.HandleKeyUp(e)}	/>
							</div>
							<button className="btn btn-primary btn-block" onClick={this.handleLogin.bind(this)}>登录</button>
						</div>
							
						
					</div>
				</div>
			</div>
			
		)
	}
}

export default Login;